package com.cart.services;

import com.cart.models.User;
import com.cart.utils.FileUtil;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

public class UserRepositoryImpl implements UserRepository {

    private List<User> users = new ArrayList<>();
    private final String USERS_FILE = "users"; // 用户数据文件

    // 在启动时读取数据
    public UserRepositoryImpl() throws InvocationTargetException {
        List<User> loadedUsers = FileUtil.readFromFile(USERS_FILE, User.class);
        if (loadedUsers != null) {
            users = loadedUsers;
        }
    }

    @Override
    public List<User> findAllCustomers() {
        List<User> customers = new ArrayList<>();
        for (User user : users) {
            if ("1".equals(user.getType())) {
                customers.add(user);
            }
        }
        return customers;
    }

    @Override
    public User findById(int id) {
        for (User user : users) {
            if (user.getId() == id) {
                return user;
            }
        }
        return null;
    }

    @Override
    public User findByUsername(String username) {
        for (User user : users) {
            if (user.getUsername().equals(username)) {
                return user;
            }
        }
        return null;
    }

    @Override
    public void save(User user) throws InvocationTargetException {
        delete(user.getId());
        users.add(user);
        saveToFile();
        users = FileUtil.readFromFile(USERS_FILE, User.class);
    }

    @Override
    public void updatePassword(int id, String password) {
        User user = findById(id);
        if (user != null) {
            user.setPassword(password); // 更新为加密后的密码
        }
    }

    @Override
    public void delete(int id) {
        users.removeIf(user -> user.getId() == id);
    }

    // 程序退出时将用户信息保存到文件
    public void saveToFile() {
        FileUtil.writeToFile(USERS_FILE, users);
    }
}
